import React, { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios';
import { Input, Space, Table, Button, Modal, Form } from 'antd';
import { useAppDispatch, useAppSelector } from './app/hooks';
import { fetchList } from './app/list/listSlice';
import { ListState } from './app/list/listSlice'
function App() {
  const list = useAppSelector(state => state.list.list);
  const [q, setQ] = useState('')
  const [open, setOpen] = useState(false)
  const dispatch = useAppDispatch()
  const [form] = Form.useForm()
  useEffect(() => {
    dispatch(fetchList(q))
  }, [q])

  const columns = [{
    title: 'id',
    dataIndex: 'id',
    key: 'id'
  }, {
    title: 'title',
    dataIndex: 'title',
    key: 'title'
  }, {
    title: 'desc',
    dataIndex: 'desc',
    key: 'desc'
  }, {
    title: 'price',
    dataIndex: 'price',
    key: 'price'
  }, {
    title: 'opration',
    key: 'opration',
    render(row: ListState) {
      return <Space>
        <Button type="primary" danger onClick={() => handleClick(row.id)}>删除</Button>
        <Button type="primary" onClick={() => handleModify(row)}>编辑</Button>
      </Space>
    }
  }]
  const handleClick = async (id: string) => {
    await axios.delete('/api/list/' + id);
    dispatch(fetchList(q))
  }

  const handleEdit = async (id: string, data: ListState) => {
    await axios.post('/api/list/' + id, data);
    dispatch(fetchList(q))
  }
  const handleModify = (row: ListState) => {
    setOpen(true)
    form.setFieldsValue(row)
  }

  return (
    <div>
      <Input.Search value={q} onChange={e => setQ(e.target.value)}></Input.Search>
      <Table dataSource={list} columns={columns} rowKey={'id'}></Table>

      <Modal open={open} title="修改" onCancel={() => setOpen(false)} onOk={() => {
        setOpen(false);
        const row = form.getFieldsValue();
        handleEdit(row.id, row)
      }}>
        <Form form={form}>
          <Form.Item name="id" label="id">
            <Input disabled></Input>
          </Form.Item>
          <Form.Item name="title" label="title">
            <Input></Input>
          </Form.Item>
          <Form.Item name="price" label="price">
            <Input></Input>
          </Form.Item>
          <Form.Item name="desc" label="desc">
            <Input></Input>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default App;
